<template>
	<view>
		<view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">
			{{ajax.loadText}}
		</view>
		<view class="box-1" id="list-box">
			<view class="talk-list">
				<view v-for="(item,index) in talkList" :key="index" :id="'a'+ item.id">
					<!-- 文字内容 -->
					<view v-if="item.type == '1'" class="item flex_col"
						:class=" item.member_id == member_id && item.is_outuser_sender == is_outuser? 'push':'pull' ">
						<image :src="item.avatar" mode="aspectFill" class="pic"></image>
						<view class="">
							<view class="name-text" v-if="item.member_id !== member_id">
								{{item.nickname}}
							</view>
							<view class="content" v-if="item.is_warn == '0'"><text
									:selectable="true">{{item.content}}</text></view>
							<view class="" v-else @click="getMoreWarn(item)">
								<view class="content" style="color: #fa3534;"><text
										:selectable="true">{{item.content}}</text></view>
								<view class="" style="font-size: 24rpx;color: #909399 ;">
									该项目可能已被申请
								</view>
							</view>

						</view>
					</view>
					<!-- 图片内容 -->
					<view v-if="item.type == '2'" class="item flex_col"
						:class=" item.member_id == member_id && item.is_outuser_sender == is_outuser? 'push':'pull' ">
						<image :src="item.avatar" mode="aspectFill" class="pic"></image>
						<view>
							<view class="name-text" v-if="item.member_id !== member_id">
								{{item.nickname}}
							</view>
							<u--image :showLoading="true" :src="item.content" width="130px" height="130px"
								@click="openPhoto(item.content)"></u--image>
						</view>

					</view>

				</view>
			</view>
		</view>

		<view class="box-2">
			<view class="flex_col">
				<view class="flex_grow">
					<input type="text" class="content" v-model="content" placeholder="请输入聊天内容"
						placeholder-style="color:#DDD;" :cursor-spacing="6">
				</view>
				<button class="send" @tap="sendMessage()" v-if="content !== ''">发送</button>
				<view style="margin-left: 20rpx;" v-else>
					<u-icon name="plus-circle" size="25" @click="selectImg"></u-icon>
				</view>
			</view>
		</view>


		<u-popup :show="pop_show" mode="center" round="5" :closeOnClickOverlay="true" @close="close" @open="open">
			<view class="" style="text-align: center;">
				相关内容
			</view>
			<scroll-view scroll-y="true" class="pop-box">
				<view class="item" v-for="item in warn_info_list" @click="handleRemind(item)">
					<image :src="item.avatar" mode=""></image>
					<view class="right">
						<view class="name-time">
							<view class="name">
								{{item.nickname}}
							</view>

							<view class="">
								{{item.add_time}}
							</view>
						</view>

						<view class="content">
							<text style="color: #3c9cff;">{{'(' + item.name+')'}}</text>
							<text>{{item.content}}</text>
						</view>
					</view>

				</view>
			</scroll-view>

		</u-popup>

		<view class="" style="height: 100rpx;">

		</view>
	</view>
</template>

<script>
	var timer;
	export default {
		data() {
			return {
				token: '',
				member_id: '',
				gid: '',
				is_outuser: '',
				pop_show: false,
				warn_info_list: [],

				talkList: [],
				ajax: {
					rows: 20, //每页数量
					page: 1, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '',

				photos: '',
				msgId: ''
			}
		},
		/* mounted() {
			this.$nextTick(() => {
				this.getHistoryMsg();
				
			});
		}, */
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				// this.getHistoryMsg();
			}
		},
		onLoad(val) {
			this.token = uni.getStorageSync('chat_token') || ''
			this.member_id = uni.getStorageSync('chat_member_id') || ''
			this.is_outuser = uni.getStorageSync('chat_is_outuser') || ''
			this.gid = val.gid || ''
			this.getDetail()
			this.getInfo()

			// 从相关内容点击进入
			if (val.comeInfo == '1') {
				this.msgId = '#a' + val.msgId;
			} else {

			}


		},
		onReady() {
			if (this.msgId !== '') {

				setTimeout(() => {
					/* const query = uni.createSelectorQuery().in(this);
					console.log(query.select(this.msgId))
					query.select(this.msgId).boundingClientRect(data => {
						console.log("得到布局位置信息" + JSON.stringify(data));
						console.log("节点离页面顶部的距离为" + data.top);
						uni.pageScrollTo({
							duration: 300,
							scrollTop: data.top
						})
					}).exec(); */
					
					uni.pageScrollTo({
						duration: 300,
						selector: this.msgId
					})
				}, 500)

			} else {
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
						duration: 0
					});
				}, 500)
			}
		},
		onShow() {
				timer = setInterval(() => {
					this.getDetail()
				}, 1000);
		},
		onUnload() {
			console.log('onUnload')
			clearInterval(timer)
		},
		onHide() {
			console.log('onHide')
			clearInterval(timer)
		},
		methods: {
			// 点击相关内容
			async handleRemind(item) {
				const res = await this.$myRequest({
					url: 'Chat/is_group_member',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: item.gid,
						is_outuser: this.is_outuser,
						company_id: '1',

					},
				});
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})

				// 如果点击的是本群组消息
				if (this.gid == item.gid) {
					/* const query = uni.createSelectorQuery().in(this);
					query.select('#a' + item.id).boundingClientRect(data => {
						console.log("得到布局位置信息", data);
						console.log("节点离页面顶部的距离为" + data.top);
						uni.pageScrollTo({
							duration: 300,
							scrollTop: data.top
						})
					}).exec(); */

					uni.pageScrollTo({
						duration: 300,
						selector: '#a' + item.id
					})
					return this.pop_show = false
				}

				// 已加入该群聊组
				if (res.data.datas.is_group_member == 1) {
					console.log('已加入')
					uni.navigateTo({
						url: 'ChatDetail?gid=' + item.gid + '&comeInfo=1' + '&msgId=' + item.id
					})
				} else {
					uni.showToast({
						title: '未加入该聊天组',
						icon: 'none'
					})
				}
			},

			open() {
				this.pop_show = true
				// console.log('open');
			},
			close() {
				this.pop_show = false
				// console.log('close');
			},


			// 获取相关的申请信息
			async getMoreWarn(item) {
				// 如果是外部人员无法进行查看操作
				if(this.is_outuser == '1'){
					return
				}
				
				
				const res = await this.$myRequest({
					url: 'Chat/remind_info',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: item.gid,
						is_outuser: this.is_outuser,
						company_id: '1',
						id: item.id,
						type: '1'

					},
				});
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})
				this.warn_info_list = res.data.datas.list

				this.pop_show = true
			},

			settime() {
				this.timer = setInterval(() => {
					this.getDetail()
				}, 1000);
			},

			// 点击查看图片详情
			openPhoto(val) {
				uni.previewImage({
					urls: [val],

				})
			},

			// 获取聊天组详情
			async getInfo() {
				const res = await this.$myRequest({
					url: 'Chat/chat_group_detail',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: this.gid,
						is_outuser: this.is_outuser,

					},
				});
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})

				uni.setNavigationBarTitle({
					title: res.data.datas.info[0].name
				})
			},

			// 获取聊天列表
			async getDetail() {
				const res = await this.$myRequest({
					url: 'Chat/chat_list',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: this.gid,
						is_outuser: this.is_outuser,
						p: 1,
						p_count: 9999
					},
				});
				this.ajax.loading = false;
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})
				console.log('页面数量-----' + res.data.datas.count)
				this.talkList = res.data.datas.list;
				this.talkList.reverse()


			},
			// 获取未读取聊天列表2
			async getDetail2() {
				const res = await this.$myRequest({
					url: 'Chat/chat_list',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: this.gid,
						is_outuser: this.is_outuser,
						type: '1',
						p: 1,
						p_count: 9999
					},
				});
				this.ajax.loading = false;
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})

				this.talkList.reverse()

			},


			// 获取历史消息
			getHistoryMsg() {
				if (!this.ajax.flag) {
					return; //
				}

				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
					let data = await this.joinHistoryMsg();

					console.log('----- 模拟数据格式，供参考 -----');
					console.log(data); // 查看请求返回的数据结构 

					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.page > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.talkList[0].id}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						selector = `#msg-${data[data.length-1].id}`;
					}

					// 将获取到的消息数据合并到消息数组中
					this.talkList = [...data, ...this.talkList];

					// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
					this.$nextTick(() => {
						// 设置当前滚动的位置
						this.setPageScrollTo(selector);

						this.hideLoadTips(true);

						if (data.length < this.ajax.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.ajax.page++;

							// 延迟 200ms ，以保证设置窗口滚动已完成
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200)
						}

					})
				}
				get();
			},
			// 拼接历史记录消息，正式项目可替换为请求历史记录接口
			joinHistoryMsg() {
				let join = () => {
					let arr = [];

					//通过当前页码及页数，模拟数据内容
					let startIndex = (this.ajax.page - 1) * this.ajax.rows;
					let endIndex = startIndex + this.ajax.rows;
					for (let i = startIndex; i < endIndex; i++) {
						arr.push({
							"id": i, // 消息的ID
							"content": `这是历史记录的第${i+1}条消息`, // 消息内容
							"type": Math.random() > 0.5 ? 1 : 0, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
							"pic": "/static/logo.png" // 头像
						})
					}

					/*
						颠倒数组中元素的顺序。将最新的数据排在本次接口返回数据的最后面。
						后端接口按 消息的时间降序查找出当前页的数据后，再将本页数据按消息时间降序排序返回。
						这是数据的重点，因为页面滚动条和上拉加载历史的问题。
					 */
					arr.reverse();

					return arr;
				}

				// 此处用到 ES6 的 Promise 知识，不懂的请自行学习。
				return new Promise((done, fail) => {
					// 无数据请求接口，由 setTimeout 模拟，正式项目替换为 ajax 即可。
					setTimeout(() => {
						let data = join();
						done(data);
					}, 1500);
				})
			},
			// 设置页面滚动位置
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取消息';
				}
			},
			// 发送信息
			send() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '正在发送'
				})
				setTimeout(() => {
					uni.hideLoading();

					// 将当前发送信息 添加到消息列表。
					let data = {
						"id": new Date().getTime(),
						"content": this.content,
						"type": 1,
						"pic": "/static/logo.png"
					}
					this.talkList.push(data);

					this.$nextTick(() => {
						// 清空内容框中的内容
						this.content = '';
						uni.pageScrollTo({
							scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
							duration: 0
						});
					})
				}, 500);
			},
			// 发送文字消息
			async sendMessage() {
				if (!this.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}

				uni.showLoading({
					mask: true,
					title: ''
				})

				const res = await this.$myRequest({
					url: 'Chat/chat_add',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: this.gid,
						type: '1',
						content: this.content,
						is_outuser: this.is_outuser,
						company_id: '1'
					},
				});
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})

				uni.hideLoading()
				this.content = '';
				uni.pageScrollTo({
					scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
					duration: 0
				});
			},

			// 发送图片消息
			async sendMessage2() {

				uni.showLoading({
					mask: true,
					title: ''
				})

				const res = await this.$myRequest({
					url: 'Chat/chat_add',
					method: 'POST',
					data: {
						token: this.token,
						member_id: this.member_id,
						gid: this.gid,
						type: '2',
						content: this.photos,
						is_outuser: this.is_outuser,
						company_id: '1'
					},
				});
				if (res.data.code != 200) return uni.showToast({
					title: res.data.datas.msg,
					icon: 'none'
				})

				uni.hideLoading()

				uni.pageScrollTo({
					scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
					duration: 0
				});
			},

			// 发送图片
			selectImg() {
				var that = this
				uni.chooseImage({
					count: 1, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: async (res) => {
						uni.showLoading({
							title: '图片发送中'
						})
						const tempFilePaths = res.tempFilePaths;
						console.log(tempFilePaths)
						// that.phone = res.tempFilePaths[0]
						uni.uploadFile({
							// url: 'https://test.control.sxpz.vip/index.php/AppApi/Chat/uploadImg',
							url: 'https://control.sxpz.vip/index.php/AppApi/Chat/uploadImg',
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'member_id': this.member_id,
								'token': this.token,
								'is_outuser': this.is_outuser
							},
							success: uploadFileRes => {
								const result = JSON.parse(uploadFileRes.data)
								this.photos = result.datas.img_url
								console.log(this.photos)
								this.sendMessage2()
							},
							fail: res => {
								console.log(res)
							}
						})
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	/* 根元素样式 设置页面背景、字体大小、字体颜色，字符间距、长单词换行 */
	page {
		background-color: #f3f3f3;
		font-size: 28rpx;
		box-sizing: border-box;
		color: #333;
		letter-spacing: 0;
		word-wrap: break-word;
	}

	.pop-box {
		width: 680rpx;
		max-height: 900rpx;

		.item {
			padding: 20rpx;
			border-bottom: 1rpx solid #F3F3F3;
			display: flex;
			flex-direction: row;
			align-items: center;

			.right {

				.name-time {
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					color: #606266;
					font-size: 26rpx;

					.name {
						margin-left: 20rpx;
					}
				}

				.content {
					width: 560rpx;

					font-size: 28rpx;
					margin-left: 10rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}


			image {
				width: 60rpx;
				height: 60rpx;
				border-radius: 12rpx;
			}
		}
	}


	.name-text {
		color: #999999;
		font-size: 24rpx;
		text-align: center;
	}



	/* 加载数据提示 */
	.tips {
		position: fixed;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 0;
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #F3F3F3;

		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 100rpx;
		}

		.content {
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 20rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #42b983;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 20rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #5fc496;
			}
		}
	}

	.talk-list {
		padding-bottom: 20rpx;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					// background-color: #fff;
					background-color: #f3f3f3;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #a0e959;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}


	/* 设置常用元素尺寸规则 */
	view,
	textarea,
	input,
	label,
	form,
	button,
	image {
		box-sizing: border-box;
	}

	/* 按钮样式处理 */
	button {
		font-size: 28rpx;
	}

	/* 取消按钮默认的边框线效果 */
	button:after {
		border: none;
	}

	/* 设置图片默认样式，取消默认尺寸 */
	image {
		display: block;
		height: auto;
		width: auto;
	}

	/* 输入框默认字体大小 */
	textarea,
	input {
		font-size: 28rpx;
	}

	;

	/* 列式弹性盒子 */
	.flex_col {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: center;
		align-content: center;
	}

	/* 行式弹性盒子 */
	.flex_row {
		display: flex;
		flex-direction: column;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;
	}

	/* 弹性盒子弹性容器 */
	.flex_col .flex_grow {
		width: 0;
		flex-grow: 1;
	}

	.flex_row .flex_grow {
		flex-grow: 1;
	}

	/* 弹性盒子允许换行 */
	.flex_col.flex_wrap {
		flex-wrap: wrap;
	}

	/* 弹性盒子居中对齐 */
	.flex_col.flex_center,
	.flex_row.flex_center {
		justify-content: center;
	}

	/* 列式弹性盒子两端对齐 */
	.flex_col.flex_space {
		justify-content: space-between;
	}

	/* 弹性盒子快速分栏 ,这里非常郁闷 uniapp 居然不支持 * 选择器 */
	.flex_col.flex_col_2>view {
		width: 50%;
	}

	.flex_col.flex_col_3>view {
		width: 33.33333%;
	}

	.flex_col.flex_col_4>view {
		width: 25%;
	}

	.flex_col.flex_col_5>view {
		width: 20%;
	}

	.flex_col.flex_col_6>view {
		width: 16.66666%;
	}

	/* 字体颜色 */
	.color_333 {
		color: #333;
	}

	.color_666 {
		color: #666;
	}

	.color_999 {
		color: #999;
	}

	.color_ccc {
		color: #ccc;
	}

	.color_fff {
		color: #fff;
	}

	.color_6dc {
		color: #6dca6d;
	}

	.color_d51 {
		color: #d51917;
	}

	.color_09f {
		color: #0099ff;
	}

	/* 背景色*/
	.bg_fff {
		background-color: #ffffff;
	}

	/* 字体大小 */
	.size_10 {
		font-size: 20rpx;
	}

	.size_12 {
		font-size: 24rpx;
	}

	.size_14 {
		font-size: 28rpx;
	}

	.size_16 {
		font-size: 32rpx;
	}

	.size_18 {
		font-size: 36rpx;
	}

	.size_20 {
		font-size: 40rpx;
	}

	/* 字体加粗 */
	.font_b {
		font-weight: bold;
	}

	/* 对齐方式 */
	.align_c {
		text-align: center;
	}

	.align_l {
		text-align: left;
	}

	.align_r {
		text-align: right;
	}

	/* 遮罩 */
	.shade {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.8);
		z-index: 100;
	}

	/* 弹窗 */
	.shade_box {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		margin: auto;
		z-index: 101;
		min-width: 200rpx;
		min-height: 200rpx;
	}
</style>
